package com.study.leetcode;

import java.util.Arrays;

public class Solution_16 {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];
        int j, k, sum;
        int len  = nums.length;
        for (int i = 0; i < len - 2; i++) {
            j = i + 1;
            k = len - 1;
            while (j < k) {
                sum = nums[i] + nums[j] + nums[k];
                if (Math.abs(sum - target) < Math.abs(result - target)) {
                    result = sum;
                }
                if (target == sum) {
                    return target;
                } else if (sum > target) {
                    k--;
                } else {
                    j++;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {0, 0, 0};
        int res = threeSumClosest(nums, 1);
        System.out.println("res = " + res);
    }
}
